package com.zrs.gmall.order.controller;

import com.zrs.gmall.common.result.Result;
import com.zrs.gmall.common.util.AuthContextHolder;
import com.zrs.gmall.order.model.OrderInfo;
import com.zrs.gmall.order.service.OrderInfoService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: zrs
 * @create: 2023-03-10
 */
@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Autowired
    private OrderInfoService orderInfoService;


    /**
     * 保存订单,响应保存后订单ID
     *
     * @param orderInfo
     * @return
     */
    @PostMapping("/auth/submitOrder")
    public Result<Long> submitOrder(HttpServletRequest request, @RequestBody OrderInfo orderInfo) {
        String userId = AuthContextHolder.getUserId(request);

        orderInfo.setUserId(Long.valueOf(userId));
        //前端页面提交流水号
        String tradeNo = request.getParameter("tradeNo");
        Long orderId = orderInfoService.submitOrder(orderInfo, tradeNo);
        return Result.ok(orderId);
    }


    /**
     * 查询当前登录用户订单列表(包括订单明细)
     *
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/auth/{page}/{limit}")
    public Result getOrderList(HttpServletRequest request, @PathVariable("page") Long page, @PathVariable("limit") Long limit, String status) {
        //1.获取登录用户ID
        String userId = AuthContextHolder.getUserId(request);
        //2.构建分页对象
        IPage<OrderInfo> iPage = new Page<>(page, limit);

        //3.调用业务逻辑查询
        iPage = orderInfoService.getOrderList(iPage, userId, status);
        return Result.ok(iPage);
    }


    /**
     * 提供给库存系统调用订单拆单接口
     *
     * @param orderId    订单ID
     * @param wareSkuMap [{"wareId":"1","skuIds":["28","29"]},{"wareId":"2","skuIds":["24"]}]
     * @return
     */
    @PostMapping("/orderSplit")
    public String orderSplit(String orderId, String wareSkuMap) {
        return orderInfoService.orderSplit(orderId, wareSkuMap);
    }
}
